#!/bin/bash

# SPAM3UK 简单管理脚本

ACTION=${1:-"status"}

case $ACTION in
    "start")
        echo "🚀 启动SPAM3UK服务..."
        
        # 检查是否有编译好的可执行文件
        if [ -f "spam3uk" ]; then
            echo "使用已编译的可执行文件..."
            sudo systemctl start spam3uk
        else
            echo "首次运行，需要编译..."
            if go build -o spam3uk main.go; then
                echo "✅ 编译成功"
                sudo systemctl start spam3uk
            else
                echo "❌ 编译失败，尝试修复Go版本问题..."
                echo "运行: ./fix-go-version.sh"
                exit 1
            fi
        fi
        
        sudo systemctl enable spam3uk
        echo "✅ 服务已启动并设置开机自启"
        ;;
        
    "stop")
        echo "🛑 停止SPAM3UK服务..."
        sudo systemctl stop spam3uk
        echo "✅ 服务已停止"
        ;;
        
    "restart")
        echo "🔄 重启SPAM3UK服务..."
        sudo systemctl restart spam3uk
        echo "✅ 服务已重启"
        ;;
        
    "status")
        echo "📊 SPAM3UK服务状态:"
        sudo systemctl status spam3uk --no-pager
        echo ""
        echo "端口监听:"
        netstat -tlnp | grep :5700 || echo "端口5700未监听"
        ;;
        
    "logs")
        echo "📝 查看SPAM3UK日志 (Ctrl+C退出):"
        sudo journalctl -u spam3uk -f
        ;;
        
    "test")
        echo "🧪 快速API测试:"
        echo "健康检查:"
        curl -s http://localhost:5700/health
        echo -e "\n车辆数据:"
        curl -s http://localhost:5700/api/vehicles?page=1&page_size=1 | head -3
        ;;
        
    "build")
        echo "🔨 编译SPAM3UK程序..."
        if go build -o spam3uk main.go; then
            echo "✅ 编译成功"
            ls -la spam3uk
        else
            echo "❌ 编译失败"
            echo "尝试运行修复脚本: ./fix-go-version.sh"
            exit 1
        fi
        ;;
        
    "fix")
        echo "🔧 修复Go版本问题..."
        if [ -f "fix-go-version.sh" ]; then
            chmod +x fix-go-version.sh
            ./fix-go-version.sh
        else
            echo "❌ 未找到修复脚本"
            exit 1
        fi
        ;;
        
    "help")
        echo "SPAM3UK 管理脚本使用说明:"
        echo "  ./manage.sh start   - 启动服务"
        echo "  ./manage.sh stop    - 停止服务"
        echo "  ./manage.sh restart - 重启服务"
        echo "  ./manage.sh status  - 查看状态"
        echo "  ./manage.sh logs    - 查看日志"
        echo "  ./manage.sh test    - 快速测试"
        echo "  ./manage.sh build   - 编译程序"
        echo "  ./manage.sh fix     - 修复Go版本问题"
        echo "  ./manage.sh help    - 显示帮助"
        ;;
        
    *)
        echo "❌ 未知操作: $ACTION"
        echo "使用 './manage.sh help' 查看帮助"
        exit 1
        ;;
esac
